<?php

namespace App\Http\Controllers;

use App\Models\SmsLog;
use App\Service\AliyunSms;
use App\Util\Tool;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use Carbon\Carbon;

class SmsController extends BaseController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function sendSmsCode(Request $request)
    {
        $phone = $request->phone ?? '';
        $ip = $request->ip ?? '';
        if (empty($phone)) {
            return $this->ResultJson(0, '手机号不能为空', []);
        }
        if (!Tool::checkMobile($phone)) {
            return $this->ResultJson(0, '手机号不正确', []);
        }
        //检查60秒内是否发过验证码
//        if (!empty(Tool:: GetSmsvalidator($phone))) {
//            return $this->ResultJson(0, '60秒内不能重复发送', []);
//        }
        $repeat_time = 'REDIS_REPEAT_TIME' . $phone;
        $hase_repeat_time = Cache::get($repeat_time);//Redis::get($repeat_time);;
        if ($hase_repeat_time) {
            return $this->ResultJson(0, '发送验证码太频繁,请稍后再发!', []);
        }
// 获取今天开始的时间
        $startOfToday = Carbon::today();
// 获取今天结束的时间（即明天开始时的前一秒）
        $endOfToday = Carbon::tomorrow()->startOfDay()->subSecond();
        $nums = (new SmsLog())->where([['ip','=',$ip]])->whereBetween('created_at', [$startOfToday, $endOfToday])->count();
        if($nums>=15){
            return $this->ResultJson(0, '发送验证码太频繁,请稍后再发i!', []);
        }
        $phones = (new SmsLog())->where([['mobile', '=', $phone]])->whereBetween('created_at', [$startOfToday, $endOfToday])->count();
        if ($phones >= 5) {
            return $this->ResultJson(0, '您的手机号今日发送验证太频繁,请稍后再发i!', []);
        }
        $code = mt_rand(1000, 9999);
        $response = AliyunSms::SendSms($phone, ['code' => $code]);
        /**
         * 写入缓存标识用户发送短信成功
         */
        if ($response->Code == "OK") {
            //设置短信过期时间
            Cache::put($repeat_time,$code,5);
        }
        if ($response->Code == "OK") {
            return $this->ResultJson(1, '发送成功', []);
        } else {
            $data["msg"] = $response->Message;
        }
        return $this->ResultJson(0, '发送失败', $data);
    }
}
